package com.yc.index.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.yc.entity.*;
import com.yc.util.*;
import com.yc.vo.Result;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
public class IndexAction {
    @Resource
    private ResourceAction resourceAction;
    @Resource
    private UserAction userAction;

    @Value( "${web.upload-path}" )
    private String path;

    @GetMapping( {"/", "index.html"} )
    public ModelAndView index(ModelAndView mav) {
        List< Cartoon > list = resourceAction.banner();
        Map< Integer, String > map = new HashMap<>();
        for ( Cartoon cartoon : list ) {
            map.put(cartoon.getCtid(), resourceAction.banner(cartoon.getCtid()) == null ? "新旧番剧" : resourceAction.banner(cartoon.getCtid()));
        }
        mav.addObject("banner", list);
        mav.addObject("bannermap", map);
        List< Rankmonth > rankmonthList = resourceAction.queryAllRankMonth();
        List< Cartoon > hotlist = new ArrayList<>();
        for ( int i = 0; i < 10; i++ ) {
            hotlist.add(resourceAction.queryByCtid(rankmonthList.get(i).getCtid()).get(0));
        }
        mav.addObject("hotplay", hotlist);
        String[] names = {"全部", "动漫剧场", "一月新番", "四月新番"};
        List< Cartoon > newlist = new ArrayList<>();
        Map< String, List< Cartoon > > newmap = new LinkedHashMap<>();
        for ( int i = 0; i < names.length; i++ ) {
            newlist = resourceAction.queryByCsnameCartoon(names[i]);
            newmap.put(names[i], newlist);
        }
        mav.addObject("newmap", newmap);
        Map< Integer, List< Cartoon > > weekmap = new HashMap<>();
        Integer cur = -1;
        for ( Integer i : DateUtil.dateformat().keySet() ) {
            cur = i;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        List< Cartoon > weeklist = new ArrayList<>();
        for ( int i = 0; i < 7; i++ ) {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(calendar.getTime());
            int num = 0;
            if ( i == cur ) {
                weeklist = resourceAction.queryByDate(DateUtil.TimeFormat(new Date()));
                while ( weeklist.size() < 3 ) {
                    if ( num > 15 ) {
                        break;
                    }
                    calendar1.set(Calendar.DAY_OF_MONTH, calendar1.get(Calendar.DAY_OF_MONTH) - 7);
                    for ( Cartoon cartoon : resourceAction.queryByDate(DateUtil.TimeFormat(calendar1.getTime())) ) {
                        weeklist.add(cartoon);
                    }
                    num++;
                }
                weekmap.put(i, weeklist);
            } else {
                int temp = i;
                if ( i > cur ) {
                    temp = 7 - (i - cur);
                }
                calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 1);
                weeklist = resourceAction.queryByDate(DateUtil.TimeFormat(calendar.getTime()));
                calendar1.setTime(calendar.getTime());
                while ( weeklist == null || weeklist.size() < 3 ) {
                    if ( num > 15 ) {
                        break;
                    }
                    calendar1.set(Calendar.DAY_OF_MONTH, calendar1.get(Calendar.DAY_OF_MONTH) - 7);
                    for ( Cartoon cartoon : resourceAction.queryByDate(DateUtil.TimeFormat(calendar1.getTime())) ) {
                        weeklist.add(cartoon);
                    }
                    num++;
                }
                weekmap.put(temp, weeklist);
            }
        }
        mav.addObject("weekmap", weekmap);
        mav.addObject("curday", cur);
        String[] week = {"一", "二", "三", "四", "五", "六", "日"};
        List< String > strlist = Arrays.asList(week);
        mav.addObject("week", strlist);
        mav.setViewName("index");
        return mav;
    }

    @GetMapping( {"newold", "newold.html"} )
    public ModelAndView newold(ModelAndView mav) {
        index(mav);
        mav.setViewName("newold");
        return mav;
    }

    @GetMapping( "artdetail-2.html" )
    public ModelAndView ad(ModelAndView mav) {
        mav.setViewName("artdetail-2");
        return mav;
    }

    @GetMapping( "artdetail-1.html" )
    public ModelAndView test(ModelAndView mav) {
        mav.setViewName("artdetail-1");
        return mav;
    }

    @GetMapping( {"notice", "notice.html"} )
    public ModelAndView notice(ModelAndView mav) {
        mav.setViewName("notice");
        return mav;
    }

    @GetMapping( {"map.html", "map"} )
    public ModelAndView map(ModelAndView mav) {
        List< Cartoon > list = resourceAction.map();
        Map< Integer, String > map = new HashMap<>();
        for ( Cartoon cartoon : list ) {
            map.put(cartoon.getCtid(), resourceAction.banner(cartoon.getCtid()));
        }
        mav.addObject("maplist", list);
        mav.addObject("map", map);
        mav.setViewName("map");
        return mav;
    }

    @GetMapping( "search" )       //value = "cname",required = false) String cname     匹配cname字段把值赋给参数cname
    public ModelAndView search(@RequestParam( value = "cname", required = false ) String cname, @RequestParam( value = "director", required = false ) String directorname, @RequestParam( value = "protagonist", required = false ) String prota, @RequestParam( value = "ctype", required = false ) String ctype, ModelAndView mav) {
        List< Cartoon > searchlist = new ArrayList<>();
        if ( cname != null ) {
            searchlist = resourceAction.queryCname(cname);
            mav.addObject("name", cname);
        } else if ( directorname != null ) {
            searchlist = resourceAction.querydirector(directorname);
            mav.addObject("name", directorname);
        } else if ( prota != null ) {
            searchlist = resourceAction.queryprota(prota);
            mav.addObject("name", prota);
        } else if ( ctype != null ) {
            searchlist = resourceAction.queryByctype(ctype);
            mav.addObject("name", ctype);
        }
        mav.addObject("searchlist", searchlist);
        Map< Integer, String > csnamemap = new HashMap();
        Map< Integer, List< String > > pmap = new HashMap();
        Map< Integer, List< String > > dmap = new HashMap();
        Map< Integer, List< String > > tmap = new HashMap();
        for ( Cartoon cartoon : searchlist ) {
            csnamemap.put(cartoon.getCtid(), resourceAction.banner(cartoon.getCtid()));
            String protagonist = cartoon.getProtagonist();
            if ( protagonist != null ) {
                String[] protagonists = protagonist.split("/");
                List p = new ArrayList(protagonists.length);
                Collections.addAll(p, protagonists);
                pmap.put(cartoon.getCtid(), p);                //加一个判定  防止数据库中主演为空时出现空指针异常
            }
            String director = cartoon.getDirector();
            if ( director != null ) {
                String[] directors = director.split("/");
                List d = new ArrayList(directors.length);
                Collections.addAll(d, directors);
                dmap.put(cartoon.getCtid(), d);
            }
            String type = cartoon.getCtype();
            String[] types = type.split("/");
            List t = new ArrayList(types.length);
            Collections.addAll(t, types);
            tmap.put(cartoon.getCtid(), t);
        }
        List< Rankmonth > rankmonthList = resourceAction.queryAllRankMonth();
        List< Cartoon > ranklist = new ArrayList<>();
        for ( Rankmonth rank : rankmonthList ) {
            ranklist.add(resourceAction.queryByCtid(rank.getCtid()).get(0));
        }
        mav.addObject("ranklist", ranklist);
        mav.addObject("csnamemap", csnamemap);
        mav.addObject("dmap", dmap);
        mav.addObject("pmap", pmap);
        mav.addObject("tmap", tmap);
        mav.setViewName("search");
        return mav;
    }

    @RequestMapping( {"show", "show.html"} )
    public ModelAndView show(ModelAndView mav) {
        List< Categorysecord > classnames = resourceAction.queryByCid(1);
        List< Categorysecord > ctypes = resourceAction.queryByCid(2);
        List< Categorysecord > times = resourceAction.queryByCid(3);
        List< Categorysecord > versions = resourceAction.queryByCid(4);
        mav.addObject("classnames", classnames);
        mav.addObject("ctypes", ctypes);
        mav.addObject("times", times);
        mav.addObject("versions", versions);
        mav.setViewName("show");
        return mav;
    }

    @RequestMapping( "show.do" )
    public Result show(@RequestParam String classname, @RequestParam String ctype, @RequestParam String time,
                       @RequestParam String version, @RequestParam( value = "page", required = false ) Integer page,
                       @RequestParam( value = "qtype" ) String qtype) {
        Result result = new Result();
        List< Cartoon > cartoonList = resourceAction.queryjimdoo(classname, ctype, time, version, qtype);
        if ( cartoonList.size() <= 0 ) {
            result.setCode(0);
            return result;
        }
        Map map = PageUtil.pageMap(cartoonList, 18, page);
        map.put("totalNum", cartoonList.size());
        result.setData(map);
        result.setCode(1);
        return result;
    }

    @RequestMapping( "/queryAll.do" )
    @ResponseBody
    public Result queryAll() {
        Result result = new Result();
        result.setCode(1);
        result.setData(resourceAction.queryAll());
        result.setMsg("查询成功");
        return result;
    }

    @RequestMapping( "/detail" )
    public ModelAndView detail(@RequestParam int ctid, ModelAndView mav) {
        List< Cartoon > list = resourceAction.queryByCtid(ctid);
        if ( list == null || list.size() == 0 ) {
            mav.setViewName("detail");
            return mav;
        }
        //动漫资源详情获取
        Cartoon detail = list.get(0);
        mav.addObject("detail", detail);
        String protagonist = detail.getProtagonist();
        String[] protagonists = protagonist.split("/");
        String director = detail.getDirector();
        String[] directors = director.split("/");
        String type = detail.getCtype();
        String[] types = type.split("/");
        List p = new ArrayList(protagonists.length);
        Collections.addAll(p, protagonists);
        List d = new ArrayList(directors.length);
        Collections.addAll(d, directors);
        List t = new ArrayList(types.length);
        Collections.addAll(t, types);
        String csname = resourceAction.banner(detail.getCtid());
        List< Pmap > pmaps = resourceAction.queryByCtidPmap(detail.getCtid());
        List< Pmap > pname = resourceAction.queryPname(detail.getCtid());
        Map< String, List< Pmap > > map = new HashMap<>();
        if ( pname.size() == 1 ) {
            map.put(pname.get(0).getPname(), pmaps);
        } else {
            for ( Pmap p1 : pname ) {
                List< Pmap > pmapList = new ArrayList<>();
                for ( Pmap p2 : pmaps ) {
                    if ( p2.getPname().equals(p1.getPname()) ) {
                        pmapList.add(p2);
                    }
                }
                map.put(p1.getPname(), pmapList);
            }
        }
        mav.addObject("protagonists", p);
        mav.addObject("directors", d);
        mav.addObject("types", t);
        mav.addObject("csname", csname);
        mav.addObject("pmaps", map);
        //排行榜数据获取
        if ( csname == null ) {
            csname = "全部";
        }
        List< Rank > rankList = resourceAction.queryByCsname(csname);
        List< Cartoon > ranklist = new ArrayList<>();
        for ( Rank rank : rankList ) {
            ranklist.add(resourceAction.queryByCtid(rank.getCtid()).get(0));
        }
        mav.addObject("ranklist", ranklist);
        //为你推荐数据获取
        mav.addObject("referlist1", resourceAction.queryByTypes(t));
        mav.addObject("referlist2", resourceAction.queryByTypes(t));
        mav.addObject("referlist3", resourceAction.queryByTypes(t));
        //对应评论数据获取
        mav.setViewName("detail");
        return mav;
    }

    @RequestMapping( "getDiscuss.do" )
    public Result getDiscuss(@RequestParam Integer ctid) {
        Result result = new Result();
        List< Comment > commentList = resourceAction.queryByCtidComment(ctid);
        Map< Integer, List< Commentsecord > > commentmap = new LinkedHashMap<>();
        Set< Integer > userset = new HashSet<>();
        Map< Integer, User > userMap = new HashMap<>();
        if ( commentList != null && commentList.size() > 0 ) {
            for ( Comment comment : commentList ) {
                userset.add(comment.getUid());
                List< Commentsecord > commentsecordList = resourceAction.queryByCmidCommentsecord(comment.getCmid());
                if ( commentsecordList != null && commentsecordList.size() > 0 ) {
                    for ( Commentsecord commentsecord : commentsecordList ) {
                        userset.add(commentsecord.getUid());
                    }
                }
                commentmap.put(comment.getCmid(), commentsecordList);
            }
            if ( userset != null && userset.size() > 0 ) {
                for ( Integer uid : userset ) {
                    userMap.put(uid, userAction.queryByUid(uid).get(0));
                }
            }
        }
        Map map = new HashMap();
        map.put("commentList", commentList);
        map.put("totalNum", commentList.size());
        map.put("commentmap", commentmap);
        map.put("usermap", userMap);
        result.setCode(1);
        result.setData(map);
        return result;
    }

    @RequestMapping( "addcollect.do" )
    public Result collect(@RequestParam Integer uid, @RequestParam Integer ctid) {
        Result result = new Result();
        Integer flag = userAction.addCollect(uid, ctid);
        if ( flag == 1 ) {
            result.setCode(1);
            result.setMsg("收藏成功");
        } else if ( flag == 0 ) {
            result.setCode(0);
            result.setMsg("已收藏过了");
        } else {
            result.setCode(-1);
            result.setMsg("服务器出错，请联系管理员");
        }
        return result;
    }

    @RequestMapping( "cancelcollect.do" )
    public Result cancelcollect(Integer uid, Integer ctid) {
        Result result = new Result();
        Integer flag = userAction.cancelcollect(uid, ctid);
        if ( flag == 1 ) {
            result.setCode(1);
            result.setMsg("取消收藏成功");
        } else if ( flag == 0 ) {
            result.setCode(0);
            result.setMsg("未收藏该动漫");
        } else {
            result.setCode(-1);
            result.setMsg("服务器错误");
        }
        return result;
    }

    @RequestMapping( "checkCollected.do" )
    public Result checkCollected(@RequestParam Integer uid, @RequestParam Integer ctid) {
        System.out.println("uid:" + uid + "  ctid:" + ctid);
        Result result = new Result();
        List< Collect > collectList = userAction.checkCollected(uid, ctid);
        if ( collectList.size() == 1 ) {
            result.setCode(1);
        } else {
            result.setCode(0);
        }
        return result;
    }

    /**
     * 详情页用户发布评论
     *
     * @param ctid
     * @param uid
     * @param massage
     * @return
     */
    @PostMapping( "discuss.do" )
    public Result addDiscuss(@RequestParam( "ctid" ) Integer ctid, @RequestParam( "uid" ) Integer uid, @RequestParam( "massage" ) String massage) {
        Result result = new Result();
        Integer flag = resourceAction.discuss(ctid, uid, massage);
        if ( flag == 1 ) {
            result.setCode(1);
            result.setMsg("评论成功");
        } else {
            result.setCode(0);
            result.setMsg("评论失败，请重试");
        }
        return result;
    }

    /**
     * 详情页用户发布追评
     *
     * @param cmid
     * @param uid
     * @param massage
     * @return
     */
    @PostMapping( "addReview.do" )
    public Result addReview(@RequestParam( "cmid" ) Integer cmid, @RequestParam( "uid" ) Integer uid, @RequestParam( "massage" ) String massage) {
        Result result = new Result();
        Integer flag = resourceAction.addReview(cmid, uid, massage);
        if ( flag == 1 ) {
            result.setCode(1);
            result.setMsg("评论成功");
        } else {
            result.setCode(0);
            result.setMsg("评论失败，请重试");
        }
        return result;
    }

    /**
     * 点赞
     *
     * @param cmid
     * @param ctid
     * @param uid
     * @return
     */
    @RequestMapping( "addPraise.do" )
    public Result addPraise(@RequestParam( "cmid" ) Integer cmid, @RequestParam( "ctid" ) Integer ctid, @RequestParam( "uid" ) Integer uid) {
        Integer flag = resourceAction.addPraise(cmid, ctid, uid);
        Result result = new Result();
        if ( flag == 1 ) {
            result.setCode(1);
            result.setMsg("点赞成功");
        } else if ( flag == 0 ) {
            result.setCode(0);
            result.setMsg("点赞失败，该评论已不存在");
        } else {
            result.setCode(0);
            result.setMsg("服务器错误，请重试");
        }
        return result;
    }

    /**
     * 详情页用户对二级评论点赞
     *
     * @param cmid
     * @param uid
     * @param cmsid
     * @return
     */
    @PostMapping( "addRePraise.do" )
    public Result addRePraise(@RequestParam( "cmid" ) Integer cmid, @RequestParam( "uid" ) Integer uid, @RequestParam( "cmsid" ) Integer cmsid) {
        Integer flag = resourceAction.addRePraise(cmid, uid, cmsid);
        Result result = new Result();
        if ( flag == 1 ) {
            result.setCode(1);
            result.setMsg("点赞成功");
        } else if ( flag == 0 ) {
            result.setCode(0);
            result.setMsg("点赞失败，该评论已不存在");
        } else {
            result.setCode(0);
            result.setMsg("服务器错误，请重试");
        }
        return result;
    }

    /**
     * 点踩
     *
     * @param cmid
     * @param ctid
     * @param uid
     * @return
     */
    @RequestMapping( "addStamp.do" )
    public Result addStamp(@RequestParam( "cmid" ) Integer cmid, @RequestParam( "uid" ) Integer ctid, @RequestParam( "uid" ) Integer uid) {
        Integer flag = resourceAction.addStamp(cmid, ctid, uid);
        Result result = new Result();
        if ( flag == 1 ) {
            result.setCode(1);
            result.setMsg("点踩成功");
        } else if ( flag == 0 ) {
            result.setCode(0);
            result.setMsg("点踩失败，该评论已不存在");
        } else {
            result.setCode(0);
            result.setMsg("服务器错误，请重试");
        }
        return result;
    }

    /**
     * 详情页用户对二级评论点踩
     *
     * @param cmid
     * @param uid
     * @param cmsid
     * @return
     */
    @PostMapping( "addReStamp.do" )
    public Result addReStamp(@RequestParam( "cmid" ) Integer cmid, @RequestParam( "uid" ) Integer uid, @RequestParam( "cmsid" ) Integer cmsid) {
        Integer flag = resourceAction.addReStamp(cmid, uid, cmsid);
        Result result = new Result();
        if ( flag == 1 ) {
            result.setCode(1);
            result.setMsg("点踩成功");
        } else if ( flag == 0 ) {
            result.setCode(0);
            result.setMsg("点踩失败，该评论已不存在");
        } else {
            result.setCode(0);
            result.setMsg("服务器错误，请重试");
        }
        return result;
    }

    @RequestMapping( "play" )
    public ModelAndView play(ModelAndView mav, @RequestParam Integer ctid,
                             @RequestParam( value = "cpname", required = false ) String cpname,
                             @RequestParam( value = "pname", required = false ) String pname) {
        if ( cpname == null ) {
            cpname = "双辞动漫①";
        }
        if ( pname == null ) {

        }
        detail(ctid, mav);
        ObjectMapper objectMapper = new ObjectMapper();
        List< String > t = objectMapper.convertValue(mav.getModel().get("types"), ArrayList.class);
        mav.addObject("preferlist", resourceAction.queryByTypesOrderByCscore(t));
        Map< String, String > map = new HashMap();
        map.put("cpname", cpname);
        map.put("pname", pname);
        mav.addObject("playmap", map);
        Gson gson = new Gson();
        String playmapstr = gson.toJson(map);
        mav.addObject("playmapstr", playmapstr);
        mav.addObject("ctid", ctid);
        List< Pmap > list = resourceAction.queryByCtidPmap(ctid);
        for ( int i = 0; i < list.size(); i++ ) {
            if ( list.get(i).getPname().equals(pname) && list.get(i).getCpname().equals(cpname) ) {
                mav.addObject("playaddress", list.get(i).getPlayaddress());
                if ( i < list.size() - 1 && list.get(i).getPname().equals(list.get(i + 1).getPname()) ) {
                    mav.addObject("nextaddress", "/play?ctid=" + list.get(i + 1).getCtid() + "&cpname=" + list.get(i + 1).getCpname() + "&pname=" + list.get(i + 1).getPname());
                } else {
                    mav.addObject("nextaddress", null);
                }
                if ( i > 0 && list.get(i).getPname().equals(list.get(i - 1).getPname()) ) {
                    mav.addObject("preaddress", "/play?ctid=" + list.get(i - 1).getCtid() + "&cpname=" + list.get(i - 1).getCpname() + "&pname=" + list.get(i - 1).getPname());
                } else {
                    mav.addObject("preaddress", null);
                }
                break;
            }
        }
        mav.setViewName("play");
        return mav;
    }

    @PostMapping( "addPlays.do" )
    @ResponseBody
    public Result addPlays(@RequestParam( value = "uid" ) Integer uid, @RequestParam( value = "ctid" ) Integer ctid,
                           @RequestParam( value = "pname" ) String pname, @RequestParam( value = "cpname" ) String cpname) {
        Result result = new Result();
        Pmap pmap = resourceAction.queryPlayAddress(ctid, pname, cpname).get(0);
        System.out.println(pmap.toString());
        List< Record > recordList = userAction.queryByUidAndCtid(uid, ctid);
        Integer flag = -1;
        if ( recordList == null || recordList.size() == 0 ) {
            flag = userAction.addRecord(uid, ctid, pmap.getPid());
        } else if ( recordList.size() == 1 ) {
            System.out.println(recordList.get(0).toString());
            flag = userAction.updateRecord(recordList.get(0), pmap.getPid());
        }
        if ( flag == 1 ) {
            result.setCode(1);
        } else {
            result.setCode(0);
        }
        return result;
    }

    /**
     * 排行榜页面跳转，通过thymeleaf进行渲染
     *
     * @param mav
     * @param name
     * @param sort
     * @return
     */
    @RequestMapping( "rank" )
    public ModelAndView rank(ModelAndView mav, @RequestParam( value = "name", required = false ) String name, @RequestParam( value = "sort", required = false ) String sort) {
        List< Cartoon > cartoonList = new ArrayList<>();
        List< String > csnamelist = new ArrayList<>();
        List< List< String > > typeList = new ArrayList<>();
        Cartoon cartoon = null;
        if ( name == null ) {
            List< Rank > rankList = null;
            if ( sort == null ) {
                rankList = resourceAction.queryAllRank();
            } else {
                rankList = resourceAction.queryByCsname(sort);
            }
            for ( int i = 0; i < rankList.size(); i++ ) {
                rankList.get(i).setRid(i + 1);
                cartoon = resourceAction.queryByCtid(rankList.get(i).getCtid()).get(0);
                cartoonList.add(cartoon);
                csnamelist.add(resourceAction.banner(rankList.get(i).getCtid()));
                String type = cartoon.getCtype();
                String[] types = type.split("/");
                List< String > t = new ArrayList(types.length);
                Collections.addAll(t, types);
                typeList.add(t);
            }
            mav.addObject("rankList", rankList);
            mav.addObject("cartoonList", cartoonList);
        } else if ( "week".equals(name) ) {
            List< Rankweek > rankList = null;
            if ( sort == null ) {
                rankList = resourceAction.queryAllRankWeek();
            } else {
                rankList = resourceAction.queryByCsnameWeek(sort);
            }
            for ( int i = 0; i < rankList.size(); i++ ) {
                rankList.get(i).setRwid(i + 1);
                cartoon = resourceAction.queryByCtid(rankList.get(i).getCtid()).get(0);
                cartoonList.add(cartoon);
                csnamelist.add(resourceAction.banner(rankList.get(i).getCtid()));
                String type = cartoon.getCtype();
                String[] types = type.split("/");
                List< String > t = new ArrayList(types.length);
                Collections.addAll(t, types);
                typeList.add(t);
            }
            mav.addObject("rankList", rankList);
            mav.addObject("cartoonList", cartoonList);
        } else if ( "month".equals(name) ) {
            List< Rankmonth > rankList = null;
            if ( sort == null ) {
                rankList = resourceAction.queryAllRankMonth();
            } else {
                rankList = resourceAction.queryByCsnameMonth(sort);
            }
            for ( int i = 0; i < rankList.size(); i++ ) {
                rankList.get(i).setRmid(i + 1);
                cartoon = resourceAction.queryByCtid(rankList.get(i).getCtid()).get(0);
                cartoonList.add(cartoon);
                csnamelist.add(resourceAction.banner(rankList.get(i).getCtid()));
                String type = cartoon.getCtype();
                String[] types = type.split("/");
                List< String > t = new ArrayList(types.length);
                Collections.addAll(t, types);
                typeList.add(t);
            }
            mav.addObject("rankList", rankList);
            mav.addObject("cartoonList", cartoonList);
        }
        mav.addObject("typeList", typeList);
        mav.addObject("name", name);
        mav.addObject("sort", sort);
        mav.addObject("csnameList", csnamelist);
        mav.setViewName("rank");
        return mav;
    }

    @RequestMapping( "typedetail" )
    public ModelAndView typedetail(ModelAndView mav, @RequestParam String name) {
        List< Cartoon > list = resourceAction.queryByCsnameCartoon(name);
        mav.addObject("typedetaillist", list);
        mav.addObject("typedetailname", name);
        mav.setViewName("typedetail");
        return mav;
    }

    /**
     * 用户界面跳转
     *
     * @param mav
     * @return
     */
    @RequestMapping( "user" )
    public ModelAndView user(ModelAndView mav) {
        mav.setViewName("user");
        return mav;
    }

    /**
     * 登录页面跳转
     *
     * @param mav
     * @return
     */
    @RequestMapping( {"login", "login.html"} )
    public ModelAndView login(ModelAndView mav) {
        mav.setViewName("login");
        return mav;
    }

    /**
     * 登陆验证
     *
     * @param name
     * @param password
     * @param request
     * @return
     */
    @PostMapping( "login.do" )
    public Result CheckLogin(@RequestParam( value = "name" ) String name, @RequestParam( value = "password" ) String password, HttpServletRequest request) {
        Result result = userAction.login(name, password);
        if ( result.getData() != null ) {
            request.getSession().setAttribute("name", result.getData());
        }
        return result;
    }

    @PostMapping( "user/selectuser" )
    public Result selectuser(HttpServletRequest request) {
        String ucount = (String) request.getSession().getAttribute("name");
        return userAction.selectuser(ucount);
    }

    @PostMapping( "user/sendmail" )
    public Result sendmail(User user) {
        Result result = userAction.sendmail(user);
        return result;
    }

    @PostMapping( "user/register" )
    public Result register(@RequestBody Map map) {
        Result result = userAction.register(map);
        return result;
    }

    @PutMapping( "user/modify" )
    public Result modify(@RequestBody User user) {
        Result result = userAction.modify(user);
        return result;
    }

    @PutMapping( "user/removemail" )
    public Result removemail(@RequestParam( value = "ucount" ) String ucount, @RequestParam( value = "email" ) String email, @RequestParam( value = "mailcode" ) String mailcode) {
        Result result = userAction.removemail(ucount, email, mailcode);
        return result;
    }

    @RequestMapping( {"favs.html", "favs"} )
    public ModelAndView favs(ModelAndView mav) {
        mav.setViewName("favs");
        return mav;
    }

    /**
     * 查询所有收藏，显示在页面
     *
     * @param request
     * @return
     */
    @PostMapping( "getcollect.do" )
    @ResponseBody
    public Result querycollect(HttpServletRequest request, @RequestParam( value = "page", required = false ) Integer page) {
        Result result = new Result();
        String ucount = request.getSession().getAttribute("name").toString();
        List< Collect > collects = userAction.querycollect(ucount);
        Map< Integer, Cartoon > cartoonMap = new HashMap<>();
        Map< Integer, String > stringMap = new HashMap<>();
        for ( Collect collect : collects ) {
            cartoonMap.put(collect.getCtid(), resourceAction.queryByCtid(collect.getCtid()).get(0));
            stringMap.put(collect.getCtid(), resourceAction.banner(collect.getCtid()));
        }
        Map map = PageUtil.pageMap(collects, 5, page == null ? 1 : page);
        map.put("cartoonMap", cartoonMap);
        map.put("stringMap", stringMap);
        result.setCode(1);
        result.setData(map);
        return result;
    }

    /**
     * 取消某一个收藏
     *
     * @param request
     * @param ctid
     * @return
     */
    @PostMapping( "collect/deletecollect" )
    @ResponseBody
    public Result deletecollect(HttpServletRequest request, @RequestParam Integer ctid) {
        String ucount = request.getSession().getAttribute("name").toString();
        return userAction.deletecollect(ucount, ctid);
    }

    /**
     * 取消所有或多个收藏
     *
     * @param request
     * @param str
     * @return
     */
    @PostMapping( "collect/deletecollectList" )
    @ResponseBody
    public Result deletecollectList(HttpServletRequest request, @RequestParam String str) {
        String ucount = request.getSession().getAttribute("name").toString();
        return userAction.deletecollectList(ucount, str);
    }

    /**
     * 检验用户是否登录
     *
     * @param session
     * @return
     */
    @PostMapping( "CheckLogin.do" )
    public Result CheckLogin(HttpSession session) {
        Result result = new Result();
        try {
            String name = session.getAttribute("name").toString();
            result = userAction.selectuser(name);
            result.setCode(1);
            result.setMsg("");
        } catch ( Exception e ) {
            result.setCode(0);
        }
        return result;
    }

    @RequestMapping( "exitlogin.do" )
    public Result exitlogin(HttpSession session) {
        Result result = new Result();
        session.setAttribute("name", null);
        result.setCode(1);
        result.setMsg("退出成功");
        return result;
    }

    @RequestMapping( "/findpass.html" )
    public ModelAndView findpass(ModelAndView mav) {
        mav.setViewName("findpass");
        return mav;
    }

    @PutMapping( "user/findpass" )
    public Result findpass(@RequestBody Map map) {
        Result result = userAction.findpass(map);
        return result;
    }

    @RequestMapping( {"plays", "plays.html"} )
    public ModelAndView plays(ModelAndView mav, HttpSession session) {
        try {
            String name = session.getAttribute("name").toString();
            mav.setViewName("plays");
        } catch ( Exception e ) {
            mav.setViewName("redirect:/login.html");
        }
        return mav;
    }

    @PostMapping( "getPlays.do" )
    @ResponseBody
    public Result getPlays(@RequestParam( value = "uid" ) Integer uid, @RequestParam( value = "page", required = false ) Integer page) {
        Result result = new Result();
        List< Record > recordList = new ArrayList<>();
        try {
            recordList = userAction.queryByUidRecord(uid);
            result.setCode(1);
            if ( recordList != null && recordList.size() > 0 ) {
                Map< Integer, Cartoon > cartoonMap = new HashMap<>();
                Map< Integer, String > stringMap = new HashMap<>();
                Map< Integer, Pmap > pmapMap = new HashMap<>();
                for ( Record record : recordList ) {
                    cartoonMap.put(record.getCtid(), resourceAction.queryByCtid(record.getCtid()).get(0));
                    String csname = resourceAction.banner(record.getCtid());
                    stringMap.put(record.getCtid(), csname == null || csname.equals("") ? "新旧番剧" : csname);
                    pmapMap.put(record.getPid(), resourceAction.queryByPid(record.getPid()).get(0));
                }
                Map map = PageUtil.pageMap(recordList, 5, page == null ? 1 : page);
                map.put("cartoonMap", cartoonMap);
                map.put("csnameMap", stringMap);
                map.put("pmapMap", pmapMap);
                result.setData(map);
            } else {
                result.setData(recordList);
            }
        } catch ( Exception e ) {
            result.setCode(0);
            result.setMsg("服务器响应超时，请稍后重试");
        }
        return result;
    }

    @RequestMapping( "deletePlays.do" )
    @ResponseBody
    public Result deletePlays(Integer rcid) {
        Result result = new Result();
        Integer flag = -1;
        try {
            flag = userAction.deleteByRcid(rcid);
            if ( flag == 1 ) {
                result.setCode(1);
                result.setMsg("删除成功");
            } else if ( flag == 0 ) {
                result.setCode(0);
                result.setMsg("删除失败，该记录已不存在");
            } else {
                result.setCode(-1);
                result.setMsg("服务器出错，请联系管理员");
            }
        } catch ( Exception e ) {
            result.setCode(0);
            result.setMsg("删除失败，服务器响应时间过长，请稍后重试");
        }
        return result;
    }

    @RequestMapping( "deleteAllPlays.do" )
    @ResponseBody
    public Result deleteAllPlays(Integer uid) {
        Result result = new Result();
        Integer flag = -1;
        try {
            flag = userAction.deleteAllPlays(uid);
            if ( flag > 0 ) {
                result.setCode(1);
                result.setMsg("删除所有记录成功");
            } else if ( flag == 0 ) {
                result.setCode(0);
                result.setMsg("删除失败，记录已为空");
            } else {
                result.setCode(-1);
                result.setMsg("服务器出错，请联系管理员");
            }
        } catch ( Exception e ) {
            result.setCode(0);
            result.setMsg("服务器响应超时，请稍后重试");
        }
        return result;
    }

    @PostMapping( "deleteSelectedPlays.do" )
    @ResponseBody
    public Result deleteSelectedPlays(String str) {
        Result result = new Result();
        Gson gson = new Gson();
        Integer[] array = gson.fromJson(str, Integer[].class);
        Integer flag = -1;
        try {
            flag = userAction.deleteByRcidList(array);
            if ( flag == 1 ) {
                result.setCode(1);
                result.setMsg("删除成功");
            } else if ( flag == 0 ) {
                result.setCode(0);
                result.setMsg("删除失败，存在部分记录已不存在");
            } else {
                result.setCode(-1);
                result.setMsg("服务器出错，请联系管理员");
            }
        } catch ( Exception e ) {
            result.setCode(0);
            result.setMsg("删除失败，服务器响应时间过长，请稍后重试");
        }
        return result;
    }

    @RequestMapping( {"login_admin.html", "login_admin"} )
    public ModelAndView login_admin(ModelAndView mav) {
        mav.setViewName("login_admin");
        return mav;
    }

    @PostMapping( "login_admin.do" )
    public Result CheckLoginAdmin(HttpSession session, @RequestParam( value = "name" ) String name, @RequestParam( value = "password" ) String password) {
        Result result = userAction.loginAdmin(name, password);
        if ( result.getCode() == 1 ) {
            session.setAttribute("adminName", name);
        }
        return result;
    }

    @PostMapping( "CheckLoginAdmin.do" )
    public Result CheckLogin_Admin(HttpSession session) {
        Result result = new Result();
        try {
            String name = session.getAttribute("adminName").toString();
            List< Admin > adminList = userAction.queryByAdname(name);
            result.setData(adminList.get(0));
            result.setCode(1);
        } catch ( Exception e ) {
            result.setCode(0);
        }
        return result;
    }

    @RequestMapping( "exitlogin_admin.do" )
    public Result exitlogin_admin(HttpSession session) {
        Result result = new Result();
        session.setAttribute("adminName", null);
        result.setCode(1);
        result.setMsg("退出成功");
        return result;
    }

    @RequestMapping( "admin" )
    public ModelAndView admin(ModelAndView mav, HttpSession session) {
        if ( session.getAttribute("adminName") == null ) {
            mav.setViewName("redirect:/login_admin.html");
            return mav;
        }
        String name = (String) session.getAttribute("adminName");
        Admin admin = userAction.queryByAdname(name).get(0);
        mav.addObject("admindetail", admin);
        Gson gson = new Gson();
        String json = gson.toJson(admin);
        mav.addObject("admin", json);
        mav.setViewName("admin");
        return mav;
    }

    @RequestMapping( "admin_info" )
    public ModelAndView admin_info(ModelAndView mav, HttpSession session) {
        admin(mav, session);
        if ( session.getAttribute("adminName") == null ) {
            mav.setViewName("redirect:/login_admin.html");
            return mav;
        }
        mav.setViewName("admin_info");
        return mav;
    }

    @RequestMapping( {"/findpass_admin", "/findpass_admin.html"} )
    public ModelAndView findpass_admin(ModelAndView mav) {
        mav.setViewName("findpass_admin");
        return mav;
    }

    @PutMapping( "admin/findpass_admin" )
    public Result findpass_admin(@RequestBody Map map) {
        Result result = userAction.findpass_admin(map);
        return result;
    }

    @PostMapping( "updateAdminInfo.do" )
    public Result updateAdminInfo(@RequestParam( value = "admin" ) String str) {
        Result result = new Result();
        Gson gson = new Gson();
        Admin admin = gson.fromJson(str, Admin.class);
        List< Admin > adminList = new ArrayList<>();
        adminList.add(admin);
        Integer flag = userAction.updateAdminInfo(adminList);
        if ( flag == 1 ) {
            result.setCode(1);
            result.setMsg("修改成功");
        } else if ( flag > 1 ) {
            result.setCode(0);
            result.setMsg("服务器错误，联系管理员");
        } else if ( flag < 1 ) {
            result.setCode(0);
            result.setMsg("修改失败");
        }
        return result;
    }

    @RequestMapping( "admin_updatepwd" )
    public ModelAndView admin_updatepwd(ModelAndView mav, HttpSession session) {
        admin(mav, session);
        if ( session.getAttribute("adminName") == null ) {
            mav.setViewName("redirect:/login_admin.html");
            return mav;
        }
        mav.setViewName("admin_updatepwd");
        return mav;
    }

    @PostMapping( "admin_updatepwd.do" )
    public Result admin_updatepwd(@RequestParam( value = "admin" ) String str, @RequestParam String newpwd) {
        Result result = new Result();
        Gson gson = new Gson();
        Admin admin = gson.fromJson(str, Admin.class);
        List< Admin > admins = userAction.queryByAdname(admin.getAdcount());
        Admin oldadmin = admins.get(0);
        if ( !oldadmin.getPassword().equals(admin.getPassword()) ) {
            result.setCode(0);
            result.setMsg("密码错误，请确认密码后重试");
            return result;
        }
        List< Admin > adminList = new ArrayList<>();
        adminList.add(admin);
        Integer flag = userAction.updateAdminPwd(adminList, newpwd);
        if ( flag == 1 ) {
            result.setCode(1);
            result.setMsg("更新密码成功");
        } else if ( flag > 1 ) {
            result.setCode(0);
            result.setMsg("服务器错误，联系管理员");
        } else if ( flag < 1 ) {
            result.setCode(0);
            result.setMsg("更新密码失败");
        }
        return result;
    }

    @RequestMapping( "addCartoon" )
    public ModelAndView addCartoon(ModelAndView mav, HttpSession session) {
        admin(mav, session);
        if ( session.getAttribute("adminName") == null ) {
            mav.setViewName("redirect:/login_admin.html");
            return mav;
        }
        mav.setViewName("addCartoon");
        return mav;
    }

    @PostMapping( "addCartoon.do" )
    public Result addCartoon(@RequestParam( value = "cname" ) String cname, @RequestParam( value = "alias" ) String alias, @RequestParam( value = "cstate" ) String cstate, @RequestParam( value = "protagonist" ) String protagonist,
                             @RequestParam( value = "director" ) String director, @RequestParam( value = "showYear" ) String showYear, @RequestParam( value = "showTime" ) String showTime, @RequestParam( value = "showArea" ) String showArea,
                             @RequestParam( value = "chour" ) Integer chour, @RequestParam( value = "lastDate" ) String lastDate, @RequestParam( value = "synopsis" ) String synopsis, @RequestParam( value = "cimage" ) String cimage,
                             @RequestParam( value = "ctype" ) String ctype, @RequestParam( value = "clanguage" ) String clanguage, @RequestParam( value = "cscore" ) Float cscore, @RequestParam( value = "commentnum" ) Integer commentnum,
                             @RequestParam( value = "edition" ) String edition, @RequestParam( value = "classname" ) String classname) {
        Cartoon cartoon = new Cartoon();
        cartoon.setCname(cname);
        cartoon.setAlias(alias);
        cartoon.setProtagonist(protagonist);
        cartoon.setCstate(cstate);
        cartoon.setDirector(director);
        cartoon.setShowYear(showYear);
        cartoon.setShowTime(showTime);
        cartoon.setShowArea(showArea);
        cartoon.setChour(chour);
        cartoon.setLastDate(lastDate);
        cartoon.setSynopsis(synopsis);
        cartoon.setCimage(cimage);
        cartoon.setCtype(ctype);
        cartoon.setClanguage(clanguage);
        cartoon.setCscore(cscore);
        cartoon.setCommentnum(commentnum);
        List< Cartoon > list = new ArrayList<>();
        list.add(cartoon);
        Result result = new Result();
        //尝试向cartoon表里添加数据
        if ( resourceAction.addCartoon(list) != 1 ) {
            result.setCode(0);
            result.setMsg("添加失败");
            return result;
        }
        //添加成功后根据动漫名从cartoon表中查询出对应的数据返回
        list = resourceAction.queryByCname(cartoon.getCname());
        //根据类型从categorysecord查询出对应的csid
        List< Categorysecord > categorysecordList = resourceAction.queryByCsnameCS(list, edition, classname);
        //根据ctid和csid向cmap表插入数据
        if ( resourceAction.addCmap(list.get(0).getCtid(), categorysecordList) != 1 ) {
            result.setCode(0);
            result.setMsg("添加失败");
            return result;
        }
        result.setCode(1);
        result.setMsg("添加成功");
        return result;
    }

    @RequestMapping( "addPlay" )
    public ModelAndView addPlay(ModelAndView mav, HttpSession session) {
        admin(mav, session);
        if ( session.getAttribute("adminName") == null ) {
            mav.setViewName("redirect:/login_admin.html");
            return mav;
        }
        mav.setViewName("addPlay");
        return mav;
    }

    @RequestMapping( "queryByCname.do" )
    public Result queryByCname(@RequestParam( value = "cname" ) String cname, @RequestParam( value = "pname", required = false ) String pname) {
        Result result = new Result();
        List< Cartoon > cartoonList = resourceAction.queryByCname(cname);
        if ( cartoonList == null || cartoonList.size() == 0 ) {
            result.setCode(0);
            result.setMsg("该动漫不存在，请确认后进行查询");
            return result;
        }
        Cartoon cartoon = cartoonList.get(0);
        if ( pname == null || pname.equals("") ) {
            result.setCode(1);
            result.setMsg("动漫资源查询成功");
            Map map = new HashMap();
            map.put("cartoon", cartoonList.get(0));
            String classname = resourceAction.banner(cartoon.getCtid());
            map.put("classname", classname == null || classname.equals("") ? "新旧番剧" : classname);
            map.put("edition", resourceAction.queryEdition(cartoon.getCtid()));
            result.setData(map);
            return result;
        }
        List< Pmap > pmaps = resourceAction.queryByCtidPmap(cartoon.getCtid());
        List< Pmap > pmapList = new ArrayList<>();
        for ( Pmap pmap : pmaps ) {
            if ( pmap.getPname().equals(pname) ) {
                pmapList.add(pmap);
            }
        }
        if ( pmapList == null || pmapList.size() == 0 ) {
            Pmap pmap = new Pmap();
            pmap.setCtid(cartoon.getCtid());
            pmap.setPname(pname);
            pmapList.add(pmap);
        }
        result.setCode(1);
        result.setData(pmapList);
        result.setMsg("播放资源查询成功");
        return result;
    }

    @PostMapping( "addPlay.do" )
    public Result addPlay(@RequestParam String play, @RequestParam String pname) {
        Result result = new Result();
        Gson gson = new Gson();
        Pmap[] array = gson.fromJson(play, Pmap[].class);
        List< Pmap > pmapList = Arrays.asList(array);
        if ( resourceAction.deleteByCtidPmap(pmapList.get(0).getCtid(), pname) < 0 || resourceAction.addPmap(pmapList) != 1 ) {
            result.setCode(0);
            result.setMsg("服务器出错，请联系管理员");
            return result;
        }
        result.setCode(1);
        result.setMsg("添加成功");
        return result;
    }

    @RequestMapping( "updateCartoon" )
    public ModelAndView updateCartoon(ModelAndView mav, HttpSession session) {
        admin(mav, session);
        if ( session.getAttribute("adminName") == null ) {
            mav.setViewName("redirect:/login_admin.html");
            return mav;
        }
        mav.setViewName("updateCartoon");
        return mav;
    }

    /**
     * 管理员界面：更新动漫资源信息
     *
     * @param cartoon
     * @param classname
     * @param edition
     * @return
     */
    @PostMapping( "updateCartoon.do" )
    public Result updateCartoon(@RequestParam( value = "cartoon" ) String cartoon, @RequestParam( value = "classname" ) String classname, @RequestParam( value = "edition" ) String edition) {
        Result result = new Result();
        Gson gson = new Gson();
        Cartoon list = gson.fromJson(cartoon, Cartoon.class);
        List< Cartoon > cartoonList = new ArrayList<>();
        cartoonList.add(list);
        if ( resourceAction.updateCartoon(cartoonList) != 1 || resourceAction.deleteByCtidCmap(list.getCtid()) < 0 ) {
            result.setCode(0);
            result.setMsg("服务器出错，请联系管理员");
            return result;
        }
        //根据类型从categorysecord查询出对应的csid
        List< Categorysecord > categorysecordList = resourceAction.queryByCsnameCS(cartoonList, edition, classname);
        //根据ctid和csid向cmap表插入数据
        if ( resourceAction.addCmap(cartoonList.get(0).getCtid(), categorysecordList) != 1 ) {
            result.setCode(0);
            result.setMsg("添加失败");
            return result;
        }
        result.setCode(1);
        result.setMsg("修改成功");
        return result;
    }

    /**
     * 动漫资源删除界面跳转
     *
     * @param mav
     * @param session
     * @return
     */
    @RequestMapping( "deleteCartoon" )
    public ModelAndView deleteCartoon(ModelAndView mav, HttpSession session) {
        admin(mav, session);
        if ( session.getAttribute("adminName") == null ) {
            mav.setViewName("redirect:/login_admin.html");
            return mav;
        }
        mav.setViewName("deleteCartoon");
        return mav;
    }

    /**
     * 管理员界面：根据动漫id删除动漫资源
     *
     * @param ctid
     * @return
     */
    @RequestMapping( "deleteByCtid.do" )
    public Result deleteCartoon(@RequestParam Integer ctid) {
        Result result = new Result();
        if ( resourceAction.deleteByCtid(ctid) < 0 || resourceAction.deleteByCtidCmap(ctid) < 0 || resourceAction.deleteByCtidPmap(ctid, null) < 0 ) {
            result.setCode(0);
            result.setMsg("服务器错误，删除失败");
            return result;
        }
        result.setCode(1);
        result.setMsg("删除成功");
        return result;
    }

    @RequestMapping( "manageUser" )
    public ModelAndView manageUser(ModelAndView mav, HttpSession session) {
        admin(mav, session);
        if ( session.getAttribute("adminName") == null ) {
            mav.setViewName("redirect:/login_admin.html");
            return mav;
        }
        mav.setViewName("manageUser");
        return mav;
    }

    /**
     * 管理员界面：冻结用户账号与解冻
     *
     * @param uid
     * @param isfreeze
     * @return
     */
    @RequestMapping( "freeze.do" )
    public Result freeze(@RequestParam( value = "uid" ) Integer uid, @RequestParam( value = "isfreeze" ) Boolean isfreeze) {
        Result result = new Result();
        Integer flag = userAction.freeze(uid, isfreeze);
        if ( flag < 0 ) {
            result.setCode(0);
            result.setMsg("服务器错误，操作失败");
            return result;
        } else if ( flag == 0 ) {
            result.setCode(0);
            result.setMsg("操作失败，请确认该用户是否存在");
            return result;
        }
        result.setCode(1);
        if ( isfreeze ) {
            result.setMsg("冻结成功");
        } else {
            result.setMsg("解冻成功");
        }
        return result;
    }

    @PostMapping( "queryAllUser.do" )
    public Result queryAllUser() {
        List< User > userList = userAction.queryAll();
        Result result = new Result();
        if ( userList.size() <= 0 ) {
            result.setCode(0);
            result.setMsg("查询失败，请确认是否有用户存在");
            return result;
        }
        result.setCode(1);
        result.setData(userList);
        result.setMsg("查询成功");
        return result;
    }

    @PostMapping( "user/queryByUcount.do" )
    public Result queryByUcount(@RequestParam String ucount) {
        List< User > userList = userAction.queryByUcount(ucount);
        Result result = new Result();
        if ( userList.size() <= 0 ) {
            result.setCode(0);
            result.setMsg("查询失败，请确认用户名是否存在");
            return result;
        }
        result.setCode(1);
        result.setData(userList);
        result.setMsg("查询成功");
        return result;
    }

    @RequestMapping( {"/ajax_info", "/ajax_info.html"} )
    public ModelAndView ajax_info(ModelAndView mav, HttpSession session) {
        try {
            String name = session.getAttribute("name").toString();
            mav.setViewName("ajax_info");
        } catch ( Exception e ) {
            mav.setViewName("redirect:/login.html");
        }
        return mav;
    }

    @RequestMapping( {"/info", "/info.html"} )
    public ModelAndView info(ModelAndView mav, HttpSession session) {
        try {
            String name = session.getAttribute("name").toString();
            mav.setViewName("info");
        } catch ( Exception e ) {
            mav.setViewName("redirect:/login.html");
        }
        return mav;
    }

    @RequestMapping( {"/popedom", "/popedom.html"} )
    public ModelAndView popedom(ModelAndView mav, HttpSession session) {
        try {
            String name = session.getAttribute("name").toString();
            mav.setViewName("popedom");
        } catch ( Exception e ) {
            mav.setViewName("redirect:/login.html");
        }
        mav.setViewName("popedom");
        return mav;
    }

    @RequestMapping( {"/reg", "/reg.html"} )
    public ModelAndView reg(ModelAndView mav) {
        mav.setViewName("reg");
        return mav;
    }

    @RequestMapping( "comment" )
    public ModelAndView comment(ModelAndView mav) {
        mav.setViewName("comment");
        return mav;
    }

    @PostMapping( "queryComment.do" )
    public Result comment(@RequestParam( value = "page", required = false ) Integer page) {
        Result result = new Result();
        List< Comment2 > comment2List = resourceAction.queryComment2();
        Set< Integer > userset = new HashSet<>();
        for ( Comment2 comment2 : comment2List ) {
            userset.add(comment2.getUid());
        }
        Map< Integer, User > userMap = new HashMap<>();
        for ( Integer uid : userset ) {
            userMap.put(uid, userAction.queryByUid(uid).get(0));
        }
        Map map = PageUtil.pageMap(comment2List, 6, page);
        map.put("usermap", userMap);
        result.setData(map);
        result.setCode(1);
        return result;
    }

    /**
     * 留言板发布留言
     *
     * @param uid
     * @param message
     * @return
     */
    @PostMapping( "ioo.do" )
    public Result ioo(@RequestParam Integer uid, @RequestParam String message, HttpSession session) {
        Result result = new Result();
        try {
            String name = session.getAttribute("name").toString();
        } catch ( Exception e ) {
            result.setCode(0);
            result.setMsg("您尚未登录，请先登录");
            return result;
        }
        Integer cartoonList = resourceAction.addmessage(uid, message);
        if ( cartoonList == 1 ) {
            result.setCode(1);
            result.setMsg("评论成功");
        } else {
            result.setCode(0);
            result.setMsg("评论失败");
        }
        return result;
    }

    @RequestMapping( value = "/uploadFile", method = RequestMethod.POST )
    public Result uploadFile(@RequestParam( "file" ) MultipartFile file, @RequestParam( "uid" ) Integer uid) {
        Result jm = new Result();
        String fileName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + fileName.substring(fileName.lastIndexOf("."), fileName.length());
        try {
            InputStream inputStream = file.getInputStream();
            //删除文件夹及其下面的文件
            String str = path.replace("/", "\\");
            Path oldpath = Paths.get(str + "user/" + uid);
            try {
                FileUtil.deleteFile(oldpath);
            } catch ( IOException e ) {
                e.printStackTrace();
            }
            //验证文件夹是否存在，如果文件夹不存在就创建文件夹，存在则无操作
            Path paths = Paths.get(path + "user/" + uid);
            Files.createDirectories(paths);
            //新建文件
            File file1 = new File(path + "user/" + uid + "/" + newName);
            if ( !file1.exists() ) {
                file1.createNewFile();
            }
            OutputStream os = new FileOutputStream(file1);
            int read = 0;
            byte[] bytes = new byte[1024 * 1024];
            //先读后写
            while ( (read = inputStream.read(bytes)) > 0 ) {
                byte[] wBytes = new byte[read];
                System.arraycopy(bytes, 0, wBytes, 0, read);
                os.write(wBytes);
            }
            os.flush();
            os.close();
            inputStream.close();
            User user = userAction.queryByUid(uid).get(0);
            user.setUimage("user/" + uid + "/" + file1.getName());
            if ( userAction.modify(user).getCode() != 1 ) {
                jm.setCode(0);
                jm.setMsg("数据更新失败，请重试");
                return jm;
            }
            jm.setData("user/" + uid + "/" + file1.getName());
            jm.setCode(1);
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return jm;
    }

    @RequestMapping( value = "/uploadFileAdmin", method = RequestMethod.POST )
    public Result uploadFileAdmin(@RequestParam( "file" ) MultipartFile file, @RequestParam( "adcount" ) String adcount) {
        Result jm = new Result();
        String fileName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + fileName.substring(fileName.lastIndexOf("."), fileName.length());
        try {
            Admin admin = userAction.queryByAdname(adcount).get(0);
            Integer adid = admin.getAdid();
            InputStream inputStream = file.getInputStream();
            //删除文件夹及其下面的文件
            String str = path.replace("/", "\\");
            Path oldpath = Paths.get(str + "admin/" + adid);
            try {
                FileUtil.deleteFile(oldpath);
            } catch ( IOException e ) {
                e.printStackTrace();
            }
            //验证文件夹是否存在，如果文件夹不存在就创建文件夹，存在则无操作
            Path paths = Paths.get(path + "admin/" + adid);
            Files.createDirectories(paths);
            //新建文件
            File file1 = new File(path + "admin/" + adid + "/" + newName);
            if ( !file1.exists() ) {
                file1.createNewFile();
            }
            OutputStream os = new FileOutputStream(file1);
            int read = 0;
            byte[] bytes = new byte[1024 * 1024];
            //先读后写
            while ( (read = inputStream.read(bytes)) > 0 ) {
                byte[] wBytes = new byte[read];
                System.arraycopy(bytes, 0, wBytes, 0, read);
                os.write(wBytes);
            }
            os.flush();
            os.close();
            inputStream.close();
            admin.setHeadimg("admin/" + adid + "/" + file1.getName());
            List< Admin > adminList = new ArrayList<>();
            adminList.add(admin);
            if ( userAction.updateAdminInfo(adminList) != 1 ) {
                jm.setCode(0);
                jm.setMsg("数据更新失败，请重试");
                return jm;
            }
            jm.setData("admin/" + adid + "/" + file1.getName());
            jm.setCode(1);
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return jm;
    }

    @RequestMapping( {"admin_spider", "admin_spider.html"} )
    public ModelAndView spider(ModelAndView mav, HttpSession session) {
        admin(mav, session);
        if ( session.getAttribute("adminName") == null ) {
            mav.setViewName("redirect:/login_admin.html");
            return mav;
        }
        mav.setViewName("admin_spider");
        return mav;
    }

    /**
     * 从原网站爬取数据并存到数据库中
     *
     * @return
     */
    @GetMapping( "spiderData.do" )
    @ResponseBody
    public Result spiderData() {
        Result result = new Result();
        String address = "https://www.scdmfun.cn/map.html";
//        String addr="https://www.scdmfun.cn/bangumi/sc"+id+".html";
        Map< Integer, String > updatemap = new LinkedHashMap();
        Map< Integer, String > addmap = new LinkedHashMap<>();
        try {
            URL url = new URL(address);
            Document doc = Jsoup.parse(url, 10000);
            String str = doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li:nth-child(1) > a").text();
            Elements elements = doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li");
            elements.forEach(LambdaUtils.consumerWithIndex((element, index) -> {
                //获取播放页面地址
                String addr = doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li:nth-child(" + index + ") > a").attr("href");
                addr = "https://www.scdmfun.cn" + addr;
                try {
                    Cartoon temp = SpiderHelper.getCartoon(addr);
                    List< Cartoon > cartoonList = resourceAction.queryByCname(temp.getCname());
                    if ( cartoonList != null && cartoonList.size() > 0 ) {
                        Cartoon cartoon = cartoonList.get(0);
                        if ( !cartoon.getLastDate().equals(temp.getLastDate()) ) {
                            cartoon.setLastDate(temp.getLastDate());
                            List< Pmap > tempPmapList = SpiderHelper.getPlayAdress(addr, cartoon.getCtid());
                            List< Pmap > pmapList = resourceAction.queryByCtidPmap(cartoon.getCtid());
                            List< Pmap > updatePmapList = new ArrayList<>();  //待更新集合
                            List< Pmap > addPmapList = new ArrayList<>();  //新增集合
                            for ( int i = 0; i < tempPmapList.size(); i++ ) {
                                boolean flag=true;
                                for ( int j = 0; j < pmapList.size(); j++ ) {
                                    //判断数据库中是否已存在该播放地址
                                    if ( pmapList.get(j).getPname().equals(tempPmapList.get(i).getPname()) && pmapList.get(j).getCpname().equals(tempPmapList.get(i).getCpname()) ) {
                                        // 当爬取到的数据为空时不进行操作
                                        if ( tempPmapList.get(i).getPlayaddress() != null && !tempPmapList.get(i).getPlayaddress().equals("") ) {
                                            // 比较地址是否相同，相同则跳出循环，否则加入待更新集合
                                            if ( tempPmapList.get(i).getPlayaddress().equals(pmapList.get(j).getPlayaddress()) ) {
                                                break;
                                            } else {
                                                Pmap pmap = pmapList.get(j);
                                                pmap.setPlayaddress(tempPmapList.get(i).getPlayaddress());
                                                updatePmapList.add(pmap);
                                                updatemap.put(cartoon.getCtid(), cartoon.getCname());
                                                System.out.println("更新：" + cartoon);
                                            }
                                        }
                                    }
                                }
                                // 该播放源数据库中不存在则加入新增集合
                                if ( flag ){
                                    addPmapList.add(tempPmapList.get(i));
                                }
                            }
                            if ( updatePmapList.size() > 0 ) {
                                resourceAction.updatePmap(updatePmapList);
                            }
                            if ( addPmapList.size() > 0 ) {
                                resourceAction.addPmap(addPmapList);
                            }
                        }
                        cartoon.setCommentnum(temp.getCommentnum());
                        cartoon.setCscore(temp.getCscore());
                        cartoonList.clear();
                        cartoonList.add(cartoon);
                        resourceAction.updateCartoon(cartoonList);
                    } else {
                        //新增动漫资源数据
                        //获取类型和版本，返回的对象的图片的内容为类型
                        String edition = temp.getCimage();
                        String classname = edition.contains("剧场") ? "剧场版" : "TV";
                        //调用前面的addCartoon方法添加动漫资源
                        Result tempresult = addCartoon(temp.getCname(), temp.getAlias(), temp.getCstate(), temp.getProtagonist(), temp.getDirector(), temp.getShowYear(),
                                temp.getShowTime(), temp.getShowArea(), temp.getChour(), temp.getLastDate(), temp.getSynopsis(), "", temp.getCtype(),
                                temp.getClanguage(), temp.getCscore(), temp.getCommentnum(), edition, classname);
                        if ( tempresult.getCode() == 1 ) {
                            // 根据动漫名查询出动漫id
                            Cartoon cartoon = resourceAction.queryByCname(temp.getCname()).get(0);
                            // 获取播放列表和播放地址
                            List< Pmap > tempPmapList = SpiderHelper.getPlayAdress(addr, cartoon.getCtid());
                            resourceAction.addPmap(tempPmapList);
                            //加入新增集合
                            addmap.put(cartoon.getCtid(), cartoon.getCname());
                            System.out.println("新增：" + cartoon);
                        }
                    }
                } catch ( Exception e ) {
//                    e.printStackTrace();
                }
            }));
        } catch ( IOException e ) {
            e.printStackTrace();
        }
        Map map = new HashMap();
        map.put("updatemap", updatemap);
        map.put("addmap", addmap);
        result.setCode(1);
        result.setData(map);
        return result;
    }

    @RequestMapping( {"admin_spiderByPage", "admin_spiderByPage.html"} )
    public ModelAndView spiderByPage(ModelAndView mav, HttpSession session) {
        admin(mav, session);
        if ( session.getAttribute("adminName") == null ) {
            mav.setViewName("redirect:/login_admin.html");
            return mav;
        }
        mav.setViewName("admin_spiderByPage");
        return mav;
    }

    /**
     * 根据传入的地址进行数据抓取
     * @param addr
     * @return
     */
    @PostMapping( "spiderDataByPage.do" )
    @ResponseBody
    public Result spiderDataByPage(@RequestParam(value = "addr") String addr) {
        Result result = new Result();
        if ( addr==null||"".equals(addr) ){
            result.setCode(0);
            result.setMsg("爬取失败，请先输入详情页地址");
            return result;
        }
        Map< Integer, String > updatemap = new LinkedHashMap();
        Map< Integer, String > addmap = new LinkedHashMap<>();
        try {
            Cartoon temp = SpiderHelper.getCartoon(addr);
            System.out.println("新爬取到的数据："+temp);
            List< Cartoon > cartoonList = resourceAction.queryByCname(temp.getCname());
            if ( cartoonList != null && cartoonList.size() > 0 ) {
                Cartoon cartoon = cartoonList.get(0);
                System.out.println("数据库中的数据："+cartoon);
                if ( !cartoon.getLastDate().equals(temp.getLastDate()) ) {
                    cartoon.setLastDate(temp.getLastDate());
                    List< Pmap > tempPmapList = SpiderHelper.getPlayAdress(addr, cartoon.getCtid());
                    List< Pmap > pmapList = resourceAction.queryByCtidPmap(cartoon.getCtid());
                    List< Pmap > updatePmapList = new ArrayList<>();  //待更新集合
                    List< Pmap > addPmapList = new ArrayList<>();  //新增集合
                    for ( int i = 0; i < tempPmapList.size(); i++ ) {
                        boolean flag=true;
                        for ( int j = 0; j < pmapList.size(); j++ ) {
                            //判断数据库中是否已存在该播放地址
                            if ( pmapList.get(j).getPname().equals(tempPmapList.get(i).getPname()) && pmapList.get(j).getCpname().equals(tempPmapList.get(i).getCpname()) ) {
                                // 当爬取到的数据为空时不进行操作
                                if ( tempPmapList.get(i).getPlayaddress() != null && !tempPmapList.get(i).getPlayaddress().equals("") ) {
                                    // 比较地址是否相同，相同则跳出循环，否则加入待更新集合
                                    if ( tempPmapList.get(i).getPlayaddress().equals(pmapList.get(j).getPlayaddress()) ) {
                                        flag=false;
                                        break;
                                    } else {
                                        Pmap pmap = pmapList.get(j);
                                        pmap.setPlayaddress(tempPmapList.get(i).getPlayaddress());
                                        updatePmapList.add(pmap);
                                        updatemap.put(cartoon.getCtid(), cartoon.getCname());
                                    }
                                }
                            }
                        }
                        // 该播放源数据库中不存在则加入新增集合
                        if ( flag ){
                            addPmapList.add(tempPmapList.get(i));
                        }
                    }
                    if ( updatePmapList.size() > 0 ) {
                        System.out.println("更新数据：");
                        updatePmapList.forEach(list->{
                            System.out.println(list);
                        });
                        resourceAction.updatePmap(updatePmapList);
                    }
                    if ( addPmapList.size() > 0 ) {
                        System.out.println("新增数据：");
                        addPmapList.forEach(list->{
                            System.out.println(list);
                        });
                        resourceAction.addPmap(addPmapList);
                    }
                }
                cartoon.setCommentnum(temp.getCommentnum());
                cartoon.setCscore(temp.getCscore());
                cartoonList.clear();
                cartoonList.add(cartoon);
                resourceAction.updateCartoon(cartoonList);
            } else {
                //新增动漫资源数据
                //获取类型和版本，返回的对象的图片的内容为类型
                String edition = temp.getCimage();
                String classname = edition.contains("剧场") ? "剧场版" : "TV";
                //调用前面的addCartoon方法添加动漫资源
                Result tempresult = addCartoon(temp.getCname(), temp.getAlias(), temp.getCstate(), temp.getProtagonist(), temp.getDirector(), temp.getShowYear(),
                        temp.getShowTime(), temp.getShowArea(), temp.getChour(), temp.getLastDate(), temp.getSynopsis(), "", temp.getCtype(),
                        temp.getClanguage(), temp.getCscore(), temp.getCommentnum(), edition, classname);
                if ( tempresult.getCode() == 1 ) {
                    // 根据动漫名查询出动漫id
                    Cartoon cartoon = resourceAction.queryByCname(temp.getCname()).get(0);
                    // 获取播放列表和播放地址
                    List< Pmap > tempPmapList = SpiderHelper.getPlayAdress(addr, cartoon.getCtid());
                    resourceAction.addPmap(tempPmapList);
                    //加入新增集合
                    addmap.put(cartoon.getCtid(), cartoon.getCname());
                    System.out.println("新增：" + cartoon);
                }
            }
        } catch ( Exception e ) {
//                    e.printStackTrace();
        }
        Map map = new HashMap();
        map.put("updatemap", updatemap);
        map.put("addmap", addmap);
        result.setCode(1);
        result.setData(map);
        return result;
    }
}
